package com.hamilton.erik.pt.mobile.android.widget;

import java.util.List;

import android.content.Context;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.hamilton.erik.pt.core.model.Animal;
import com.hamilton.erik.pt.mobile.android.R;

public class AnimalListAdapter extends BaseAdapter {

	private List<Animal> animals;
	private LayoutInflater layoutInflater;
	
	public AnimalListAdapter(Context context, List<Animal> animals) {
		this.animals = animals;
		layoutInflater = LayoutInflater.from(context);
	}
	
	@Override
	public int getCount() {
		return animals.size();
	}

	@Override
	public Object getItem(int index) {
		return animals.get(index);
	}

	@Override
	public long getItemId(int index) {
		return index;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		AnimalHolder animalHolder;
		
		if(convertView == null) {
			convertView = layoutInflater.inflate(R.layout.animal_row_view, null);
			
			animalHolder = new AnimalHolder();
			
			animalHolder.name = (TextView)convertView.findViewById(R.id.animal_name);
			animalHolder.type_genus_species = (TextView)convertView.findViewById(R.id.animal_type_genus_species);
			
			convertView.setTag(animalHolder);
		}
		else {
			animalHolder = (AnimalHolder)convertView.getTag();
		}
		
		String scientificName = animals.get(position).getScientificName();
		
		StringBuilder display = new StringBuilder(animals.get(position).getType());
		
		if(!TextUtils.isEmpty(scientificName)) {
			display.append(" (<i>").append(scientificName).append("</i>)");
		}
		
		animalHolder.name.setText(animals.get(position).getName());
		animalHolder.type_genus_species.setText(
				Html.fromHtml(
						display.toString()));
		
		return convertView;
	}
	
	static class AnimalHolder {
		TextView name;
		TextView type_genus_species;
	}

}
